// 题目工具方法，统一选项/答案处理逻辑

/**
 * 解析选项为纯内容数组，兼容字符串、数组、JSON
 * @param {string|array} options
 * @returns {array}
 */
export function parseOptions(options) {
  if (Array.isArray(options)) return options;
  if (typeof options === 'string') {
    const str = options.trim();
    if (str.startsWith('[') && str.endsWith(']')) {
      try {
        return JSON.parse(str);
      } catch {
        // fallback
      }
    }
    // 普通字符串分割，兼容逗号、换行、顿号
    return str.split(/[，,、\n]/).map(s => s.trim()).filter(Boolean);
  }
  return [];
}

/**
 * 选项字符串转 key-value 数组（A.内容），只处理字符串，逗号/顿号/换行分割
 * @param {string} options
 * @returns {Array<{key: string, value: string}>}
 */
export function toOptionsKV(options) {
  const arr = String(options || '').split(/[，,、\n]/).map(s => s.trim()).filter(Boolean);
  return arr.map((text, idx) => ({
    key: String.fromCharCode(65 + idx),
    value: text
  }));
}


/**
 * 标准化 correct_answer，返回选项 key（所有题型都返回 key，判断题也返回 A/B）
 * @param {object} question
 * @returns {string}
 */
export function normalizeCorrectAnswer(question) {
  const { type, correct_answer, answer, options } = question;
  const opts = toOptionsKV(options, type);
  let ans = correct_answer || answer || '';
  // 单选、多选、判断都返回 key
  if (type === 0 || type === '0' || type === 'single') {
    if (Array.isArray(ans)) ans = ans[0];
    if (typeof ans === 'string') {
      // 可能是 key 或 value
      const found = opts.find(opt => opt.key === ans || opt.value === ans);
      return found ? found.key : ans;
    }
    return ans;
  }
  if (type === 1 || type === '1' || type === 'multiple') {
    let arr = Array.isArray(ans) ? ans : String(ans).split(/[，,、]/).map(s => s.trim()).filter(Boolean);
    let keys = arr.map(a => {
      const found = opts.find(opt => opt.key === a || opt.value === a);
      return found ? found.key : a;
    });
    return keys.join(',');
  }
  if (type === 3 || type === '3' || type === 'truefalse') {
    // 判断题，返回 A/B
    if (ans === 'A' || ans === 'B') return ans;
    if (ans === '正确') return 'A';
    if (ans === '错误') return 'B';
    // 兼容 value
    const found = opts.find(opt => opt.value === ans);
    return found ? found.key : ans;
  }
  // 填空/简答
  return ans;
}

/**
 * 判断选项内容是否为正确答案（只比 value，不比 key）
 * @param {object} question
 * @param {string} optionValue
 * @returns {boolean}
 */
export function isCorrectOption(question, optionValue) {
  const correctArr = String(question.correctAnswer || question.answer || '').split(/[，,、\n]/).map(s => s.trim()).filter(Boolean);
  return correctArr.includes(optionValue);
}

/**
 * 格式化答案显示
 * @param {object} question
 * @returns {string}
 */
export function formatAnswer(question) {
  const { type } = question;
  const opts = toOptionsKV(question.options, type);
  const correct = normalizeCorrectAnswer(question);
  if (type === 0 || type === '0' || type === 'single') {
    const found = opts.find(opt => opt.key === correct);
    return found ? `${found.key}. ${found.value}` : correct;
  }
  if (type === 1 || type === '1' || type === 'multiple') {
    return correct.split(',').map(ans => {
      const found = opts.find(opt => opt.key === ans.trim());
      return found ? `${found.key}. ${found.value}` : ans.trim();
    }).join('，');
  }
  if (type === 3 || type === '3' || type === 'truefalse') {
    const found = opts.find(opt => opt.key === correct);
    return found ? `${found.key}. ${found.value}` : correct;
  }
  // 填空/简答
  return correct;
}

/**
 * 统一用于回显的选项解析，无论 options 是字符串、数组、对象数组都能转成 {key, value} 数组
 * @param {string|array} options
 * @param {number|string} type
 * @returns {Array<{key: string, value: string}>}
 */
export function parseOptionsForDisplay(options, type) {
  let arr = [];
  // 对象数组
  if (Array.isArray(options) && options.length && typeof options[0] === 'object') {
    arr = options.map(opt => opt.text || opt.value || '');
  } else if (Array.isArray(options)) {
    arr = options;
  } else if (typeof options === 'string') {
    const str = options.trim();
    if (str.startsWith('[') && str.endsWith(']')) {
      try {
        arr = JSON.parse(str);
      } catch {
        arr = str.split(/[，,、\n]/).map(s => s.trim()).filter(Boolean);
      }
    } else {
      arr = str.split(/[，,、\n]/).map(s => s.trim()).filter(Boolean);
    }
  }
  // 判断题
  if (type === 3 || type === '3') {
    if (!arr || arr.length < 2) arr = ['正确', '错误'];
    return [
      { key: 'A', value: arr[0] || '正确' },
      { key: 'B', value: arr[1] || '错误' }
    ];
  }
  // 单选/多选题
  if (type === 0 || type === '0' || type === 1 || type === '1') {
    if (!arr || arr.length < 4) while (arr.length < 4) arr.push('');
    return arr.map((text, idx) => ({ key: String.fromCharCode(65 + idx), value: String(text).replace(/^([A-D][.、: ]?)/, '').trim() }));
  }
  // 其它题型
  return arr.map((text, idx) => ({ key: String.fromCharCode(65 + idx), value: String(text).trim() }));
} 